package com.example.jeson.stocktest.mvp.adapter;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.jeson.stocktest.R;
import com.example.jeson.stocktest.entity.Stock;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * @author jeson
 */
public class StockAdapter extends RecyclerView.Adapter<StockAdapter.StockViewHolder> {

    private ArrayList<Stock> mAllStockList;

    public StockAdapter(ArrayList<Stock> stockArrayList) {
        this.mAllStockList = stockArrayList;
    }

    @Override
    public StockViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stock, parent, false);
        return new StockViewHolder(view);
    }

    @Override
    public void onBindViewHolder(StockViewHolder holder, int position) {
        holder.init(position);
    }

    @Override
    public int getItemCount() {
        return mAllStockList.size();
    }

    class StockViewHolder extends RecyclerView.ViewHolder {

        AppCompatTextView mStock;
        AppCompatImageView mStockIV;

        public StockViewHolder(View itemView) {
            super(itemView);
            mStockIV = (AppCompatImageView) itemView.findViewById(R.id.stock_iv);
            mStock = (AppCompatTextView) itemView.findViewById(R.id.stock_tv);
        }

        public void init(final int position) {
            Stock stock = mAllStockList.get(position);
            float rate = Float.valueOf(stock.px_change_rate);
            mStockIV.setImageResource(rate > 0 ? R.mipmap.ic_stock_up : R.mipmap.ic_stock_down);
            mStock.setTextColor(ContextCompat.getColor(itemView.getContext(), rate > 0 ? R.color.stock_up : R.color.stock_down));
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            String value = decimalFormat.format(rate);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(stock.name);
            stringBuilder.append(rate > 0 ? " +" : " ");
            stringBuilder.append(value);
            stringBuilder.append("%");
            mStock.setText(stringBuilder.toString());
        }
    }


}